import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Comment,TabPage,Reply,  } from 'weaver-mobile-page';
import { Icon, Tools, PhotoSwipe, FilePicker } from 'weaver-mobile';
import { renderIsTop } from '../../public';
import BackTop from '../../../public/back-to-top';
import RouteModal from '../../communication/RouteModal';
const getLabel = Tools.getLabel;

@withRouter
@inject('centerStore')
@observer
export default class Relate extends React.Component {
  static defaultProps = {
    prefixCls: 'cowork-center-relate',
  }

  constructor(props) {
    super(props);
    this.state = {
      path: props.location.pathname + '/detail',
      coworkId: '',
      multiple: false,
      showImage: false,
      index: 0,
		}
		this.photoSwipeArr = []; //存放图片预览数组
  }

  componentDidMount() {
    this.photoSwipePreview();
  }

  componentDidUpdate(){
    this.photoSwipePreview();
  }

  componentWillUnmount() {
    const {centerStore: {relateStore }} = this.props;
		relateStore.clear();

		const { closeAllModel } = relateStore;
		closeAllModel();
  }

	/* 图片查看相关功能 */
  photoSwipePreview = () => {
    const {centerStore: {relateStore}} = this.props;
    relateStore.setStoreState({ replyVisible: this.setReplyVisible });

    setTimeout(() => {
      let msgArr = document.getElementsByClassName("wm-comment-content-msg");
      let imgArr = [];
      let imgArrTemp = [];
      for(let i = 0; i < msgArr.length; i++){
        imgArrTemp = msgArr[i].getElementsByTagName("img"); 
        for(let j = 0; j < imgArrTemp.length; j++){
          imgArr.push(imgArrTemp[j]);
        }
      }

			this.photoSwipeArr = [];
      for(let k = 0; k < imgArr.length; k++){
        this.photoSwipeArr.push({url: imgArr[k].src});
        imgArr[k].onclick = () => {this.onItemClick(k)};
			}
    }, 1000);
  }

  onItemClick = (index) => {
    this.setState({
      showImage: true,
      index: index
    });
    PhotoSwipe.showImage(this.photoSwipeArr, index);
  }
  
  // 设置Reply组件的显隐
  setReplyVisible = (val) => {
    const replyRef = this.replyRef;
    if (replyRef) {
      replyRef.setState({ visible: val }, () => {
        replyRef.getInputFocus();
      });
    } else {
      window.setTimeout(()=>{
        this.setReplyVisible();
      },0)
    }
  }

  // 跳转详情页面
  toDetailPage = (e, data) => {
    e.stopPropagation();
    this.setState({coworkId: data.coworkId});
    this.props.history.push(`${this.state.path}?id=${data.coworkId}&&floor=${data.floorNum}`);
  }


  renderRightTop = (data) => {
    const { centerStore: {relateStore} } = this.props;
    const Curs = 'cowork-comment'
    return (
      <div className={`${Curs}-renderRight`}>
        {data.isTop === '1' && renderIsTop}
        {
          data.cancollect === '1' && <span className={`${Curs}-renderRight-collect`} onClick={() => relateStore.coworkDiscussOperation(data,'','collect', null, {menuType: 'relate'})}>
            {
              data.iscollect === '1' ? <Icon type='blog-concern-hot' color='#f77' size='xs' /> : <Icon type='blog-concern' color='#868686' size='xs'/>
            }
          </span>
        }
        <span className={`${Curs}-renderRight-floor`} onClick={(e) => this.toDetailPage(e, data)}>
        <a>#{data.floorNum}</a>
        </span>
      </div>
    )
  }

  renderTopDefine = (data) => {
    const { prefixCls } = this.props;
    return (
      <div className={`${prefixCls}-topDefine`}>
        {getLabel(83258,'相关主题')}：
       <a onClick={() => this.props.history.push(`${this.state.path}?id=${data.coworkId}`)}>{data.coworkName}</a>
      </div>
    )
  }

  render(){
    const {prefixCls, centerStore: {relateStore}} = this.props;
    let { relatedComment, detailReply, replyComment, commentReplyStoreMap, saveComment, replyType, quoteReply, quoteReplyStoreMap, leftConfig, setDateType } = relateStore;
    replyComment && (detailReply = commentReplyStoreMap[replyComment.replyId]);
    replyComment && (quoteReply = quoteReplyStoreMap[replyComment.replyId]);
    const reply = replyComment && (replyType === 'quote' ? quoteReplyStoreMap[replyComment.replyId] : commentReplyStoreMap[replyComment.replyId]);
    // if (replyComment) {
    //   detailReply = commentReplyStoreMap[replyComment.replyId];
    //   quoteReply = quoteReplyStoreMap[replyComment.replyId]
    // }
    const tabProps = {
      onTabClick: (tab) => {
        setDateType(tab.key);
        this.photoSwipePreview();
        this.refs.backTop.setVisible(false);
      }
    };

    const tabs = [
      {title: getLabel(332,'全部'),key:'all'},
      {title: getLabel(15537,'今天'),key:'today'},
      {title: getLabel(15539,'本周'),key:'week'},
      {title: getLabel(83223,'近一月'),key:'month'},
      {title: getLabel(83224,'近三月'),key:'quarter'},
      {title: getLabel(83225,'近一年'),key:'year'},
    ];

    const renderTopContent = (data) => {
      const { prefixCls } = this.props;
      return data.needApprove === '1' ? <div className={`${prefixCls}-renderTopContent`}>{getLabel(83261, '等待管理员审批')}</div> : '';
    }

    return (
      <div className={prefixCls}>
          <div id="tabs" className='cowork-fixTop'>
            <TabPage
              tabs={tabs}
              tabProps={tabProps}
            /> 
          </div>

          <div className={`${prefixCls}-comment`}>
            <BackTop
              ref='backTop'
              visibilityHeight='200'
              modal
              target='wm-comment-scrollview'
            >
            <Comment
              store={relatedComment}
              renderTopContent={renderTopContent}
              renderRightTop={this.renderRightTop}
              renderTopDefine={this.renderTopDefine}
            />
            </BackTop>
        </div>
        {reply && <Reply
          wrappedComponentRef={ref => this.replyRef = ref}
          store={replyType === 'quote' ? quoteReply : detailReply}
          leftConfig={leftConfig}
          placeholder={getLabel(390700, '交流内容')+'…'}
          visible={false}
          onSubmit={(data)=> saveComment(data)}
        />}
        <div style={{display: 'none'}}>
          <FilePicker
            listType='img'
            files={this.photoSwipeArr}
          />
        </div>
        <RouteModal/> 
      </div>
    );
  }
}